package com.tp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.java.Item;
import com.java.ItemAdapter;

public class Trip extends CustomWindow implements OnItemClickListener,
		OnItemSelectedListener, OnClickListener {
	TextView hotel, res, event, noDay;
	static int id_Trip, duration, allow = 1;
	static ArrayList<Item> array = new ArrayList<Item>();
	int id_TripDetail, day, id_Hotel, id_TripDetailRes, id_Res,
			id_TripDetailEvent, id_Event;
	String time;
	String des;
	Spinner trip, select_day;
	static int selectDay = 0; // neu =1 thi day da dc set tu ListTrip
	static String trip_name;
	static String startDate;
	TextView trip_info;
	ListView listView;
	List<Item> rowItems;
	String items[];
	EditText report;
	Button edit_trip;
	JSONArray jArr;
	static int setAdap = 0; // xac dinh Trip co dc goi tu Search Trip k, =1 la
							// goi tu SearchTrip
	static int selectPosition = 0;
	int selectDayPosition = 0;
	static int selectDayPosition_ = 0;
	static int day_ = 0;

	static int flag = 0; // if Trip dc goi tu ListTrip thi flag =1
	ArrayList<String> result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trip);
		this.icon.setImageResource(R.drawable.travel_icon);
		this.title.setText("Hành trình");
		trip_info = (TextView) findViewById(R.id.trip_info);
		report = (EditText) findViewById(R.id.report);
		select_day = (Spinner) findViewById(R.id.select_day);
		select_day.setOnItemSelectedListener(this);
		trip = (Spinner) findViewById(R.id.trip_name);
		edit_trip = (Button) findViewById(R.id.edit_trip);

		edit_trip.setOnClickListener(this);

		if (setAdap == 1) {

			Log.v("AA", "SearchTrip");
			items = new String[SearchTrip.trip.size()];

			items = SearchTrip.trip.toArray(items);

		} else {

			result = getTrip();
			Log.v("AA", "NotSearchTrip");
			items = new String[result.size()];
			items = result.toArray(items);

		}

		ArrayAdapter<String> adapter_trip = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, items);
		// Specify the layout to use when the list of choices appears
		adapter_trip
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		trip.setAdapter(adapter_trip);
		trip.setOnItemSelectedListener(this);
		if (flag == 1 && setAdap == 0) {
			int spinnerPosition = adapter_trip.getPosition(trip_name
					+ ", Ngày " + startDate);

			// set the default according to value
			trip.setSelection(spinnerPosition);
			flag = 0;
		}
		if (flag == 1 && setAdap == 1) {
			int spinnerPosition = adapter_trip.getPosition(trip_name
					+ ", Ngày " + startDate + ", Ngày thứ " + selectDay);

			// set the default according to value
			trip.setSelection(spinnerPosition);
			flag = 0;
		}

		if (selectPosition != 0) { // truong hop khi sua 1 dtuong, an back tro
									// ve Trip tuong ung, selectPosition duoc
									// set trong PostComment
			trip.setSelection(selectPosition);
			selectPosition = 0;
		}
		listView = (ListView) findViewById(R.id.list);
		/*
		 * if (allow == 1) listView.setOnItemClickListener(this);
		 */
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.edit_trip:
			if (allow == 1) {
				EditTrip.id_Trip = id_Trip;
				EditTrip.day = day;
				startActivity(new Intent(this, EditTrip.class));
			} else
				Toast.makeText(this,
						"Bạn không thể cập nhật hành trình này",
						Toast.LENGTH_SHORT).show();
			break;
		}

	}

	private ArrayList<String> getTrip() {
		JSONArray jArray;
		JSONObject json_data = null;
		int i;
		ArrayList<String> r = new ArrayList<String>();
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters
				.add(new BasicNameValuePair("id_User", "" + Constant.user));

		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTrip", postParameters);

			if (result != "") {

				jArray = new JSONArray(result);
				jArr = jArray;
				for (i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					/*
					 * if(json_data.getInt("id_User")==Constant.user) allow =1;
					 */
					r.add(json_data.getString("name") + ", Ngày "
							+ json_data.getString("dateStart"));
				}
			}
		} catch (JSONException e1) {

		} catch (ParseException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return r;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		// arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);
		PostComment.name = array.get(arg2).getName();
		PostComment.id = array.get(arg2).getId();
		PostComment.icon_ = array.get(arg2).getIcon();
		PostComment.type = array.get(arg2).getType();
		PostComment.id_TripDetail = id_TripDetail;
		PostComment.id_TripDetailEvent = id_TripDetailEvent;
		PostComment.id_TripDetailRes = id_TripDetailRes;
		startActivity(new Intent(this, PostComment.class));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_trip, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemSelectedListener#onItemSelected(android
	 * .widget.AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		// TODO Auto-generated method stub
		if (parent.getId() == R.id.select_day) {
			PostComment.selectDayPosition_ = pos;
			if(selectDayPosition_ != 0){
				select_day.setSelection(selectDayPosition_);
				selectDayPosition_ =0;
				}
			String day = parent.getItemAtPosition(pos).toString();
			if (id_Trip > 0) {
				array.clear();
				getTripDetailHotel(Integer.parseInt(day));
				ItemAdapter adapter2 = new ItemAdapter(this,
						R.layout.list_item, array);
				listView.setAdapter(adapter2);
			}
		} else if (parent.getId() == R.id.trip_name) {
			PostComment.selectPosition = pos; // luu lai Trip duoc chon
			// String value =
			// getListView().getItemAtPosition(position).toString();
			String value = parent.getItemAtPosition(pos).toString();
			if (setAdap == 0) {
				for (int i = 0; i < jArr.length(); i++) {
					JSONObject json_data;
					try {
						json_data = jArr.getJSONObject(i);
						if ((json_data.getString("name") + ", Ngày " + json_data
								.getString("dateStart")).equals(value)) {
							if (json_data.getInt("id_User") == Constant.user) {
								allow = 1;
								listView.setOnItemClickListener(this);
							} else {
								allow = 0;
								listView.setOnItemClickListener(null);
							}
							Trip.trip_name = json_data.getString("name");
							Trip.startDate = json_data.getString("dateStart");
							Trip.id_Trip = json_data.getInt("id_Trip");
							Trip.duration = json_data.getInt("duration");

							trip_info.setText("Tên  " + Trip.trip_name + "\n"
									+ "Ngày bắt đầu  " + Trip.startDate
									+ "\nSố ngày " + Trip.duration);
							// getTripDetailHotel(_day);
							String a[] = new String[Trip.duration];
							for (int j = 0; j < Trip.duration; j++) {
								a[j] = "" + (j + 1);
							}
							ArrayAdapter<String> adapter = new ArrayAdapter<String>(
									this, android.R.layout.simple_spinner_item,
									a);
							// Specify the layout to use when the list of
							// choices
							// appears
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							// Apply the adapter to the spinner
							select_day.setAdapter(adapter);
						
							

						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else {
				for (int m = 0; m < SearchTrip.jArr.length(); m++) {
					JSONObject json_data_;
					try {
						json_data_ = SearchTrip.jArr.getJSONObject(m);

						if ((json_data_.getString("name") + ", Ngày "
								+ json_data_.getString("dateStart")
								+ ", Ngày thứ " + json_data_.getInt("day"))
								.equals(value)) {
							if (json_data_.getInt("id_User") == Constant.user) {
								allow = 1;
								listView.setOnItemClickListener(this);
							} else {
								allow = 0;
								listView.setOnItemClickListener(null);
							}
							Trip.trip_name = json_data_.getString("name");
							Trip.startDate = json_data_.getString("dateStart");
							Trip.id_Trip = json_data_.getInt("id_Trip");
							Trip.duration = json_data_.getInt("duration");
							day_ = json_data_.getInt("day");

							trip_info.setText("Tên  " + Trip.trip_name + "\n"
									+ "Ngày bắt đầu  " + Trip.startDate
									+ "\nSố ngày " + Trip.duration);
							// getTripDetailHotel(_day);
							String a[] = new String[Trip.duration];
							for (int j = 0; j < Trip.duration; j++) {
								a[j] = "" + (j + 1);
							}

							ArrayAdapter<String> adapter = new ArrayAdapter<String>(
									this, android.R.layout.simple_spinner_item,
									a);
							// Specify the layout to use when the list of
							// choices
							// appears
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							// Apply the adapter to the spinner
							select_day.setAdapter(adapter);
							if (day_ != 0) { // truong hop day duoc xet tu
												// Search
												// Trip
								// ve Trip tuong ung, selectPosition duoc
								// set trong PostComment
								Log.v("Day", "" + day_);
								Log.v("Pos", "" + pos);
								selectDayPosition = adapter.getPosition(Integer
										.toString(day_));
								select_day.setSelection(selectDayPosition);
								day_ = 0;
								// break;

							}
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			allow = 1;
			if (setAdap == 1) {
				setAdap = 0;
				ListTrip.flag = 1;
				Intent a = new Intent(this, ListTrip.class);
				// a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(a);
			} else {

				Intent a = new Intent(this, Main.class);
				// a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(a);
			}
			return true;

		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemSelectedListener#onNothingSelected(android
	 * .widget.AdapterView)
	 */
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.report:
			// startActivity(new Intent(this, ListTrip.class));
			return true;

		}
		return false;
	}

	private void getTripDetailHotel(int _day) {

		JSONArray jArray;
		JSONObject json_data = null;
		int i;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));
		postParameters
				.add(new BasicNameValuePair("day", Integer.toString(_day)));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripDetailHotel", postParameters);

			jArray = new JSONArray(result);
			// jArr = jArray;
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_TripDetail = json_data.getInt("id_TripDetail");
				day = json_data.getInt("day");
				id_Hotel = json_data.getInt("id_Hotel");

				des = json_data.getString("description");

				array.add(new Item(R.drawable.hotel, getObject(id_Hotel),
						id_Hotel, 1));
				if (id_TripDetail > 0) {
					getTripDetailRes();
					getTripDetailEvent();
				}

			}
		} catch (JSONException e1) {

		} catch (ParseException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getTripDetailRes() {
		JSONArray jArray;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id_TripDetail)));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripDetailRes", postParameters);

			jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_TripDetailRes = json_data.getInt("id_TripDetailRes");
				time = json_data.getString("time");
				id_Res = json_data.getInt("id_Res");

				array.add(new Item(R.drawable.restaurant, getObject(id_Res),
						id_Res, 2));
			}

		} catch (JSONException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getTripDetailEvent() {
		JSONArray jArray;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id_TripDetail)));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripDetailEvent", postParameters);

			jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_TripDetailEvent = json_data.getInt("id_TripDetailEvent");
				time = json_data.getString("time");
				id_Event = json_data.getInt("id_Event");

				array.add(new Item(R.drawable.picnic, getObject(id_Event),
						id_Event, 3));
			}

		} catch (JSONException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String getObject(int id_Obj) {
		// END Convert response to string
		JSONArray jArray;
		String name = null;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id_Obj)));

		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/getObjectById", postParameters);

			jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				// Log.d("A", json_data.getString("name"));
				name = json_data.getString("name");
			}
			// return r;
		} catch (JSONException e1) {

		} catch (ParseException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return name;

	}

}
